//
//  STPersonalViewController.swift
//  SeaTransportManage
//
//  Created by guopengwen on 2021/11/26.
//

import UIKit

class STPersonalViewController: GPImagePickerController, STPersonaChangeImageDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
   
    let requestApi = GPRequestApi.init()
    var dataSource: Array<Dictionary<String, Any?>> = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.init(hexString: "#F7F7F7", alpha: 1)
        setNavBarTitle("个人资料")
        addRightBarButtonItem("编辑")
    
        addSubviewForPage()
        requestUserInfo()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        requestUserInfo()
    }
    
    func addSubviewForPage() {
        addTopBGView()
        
        view.addSubview(listView)
        let h = 320 * (kScreenWidth - 32) / 343
        listView.snp.makeConstraints { (make) in
            make.top.equalTo(10)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(h)
        }
        
        view.addSubview(loginOutBtn)
        loginOutBtn.snp.makeConstraints { (make) in
            make.bottom.equalTo(-132)
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.equalTo(48)
        }
        
        STPersonalCollectionViewCell.registerTo(listView)
        loginOutBtn.addTarget(self, action: #selector(loginOutAction), for: .touchUpInside)
    }
    
    override func rightBarButtonAction() {
        let vc = STModifyPersonalInfoViewController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func loginOutAction() {
        UserDefaults.standard.removeObject(forKey: Authorization_Key)
        let loginVC: STLoginViewController = STLoginViewController.init()
        UIApplication.shared.keyWindow?.rootViewController = loginVC
    }
    
    // UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if (indexPath.item == 0) {
            let h = 96 * (kScreenWidth - 32) / 343
            return CGSize.init(width: kScreenWidth - 32, height: h)
        } else {
            let h = 74 * (kScreenWidth - 32) / 343
            return CGSize.init(width: kScreenWidth - 32, height: h)
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = STPersonalCollectionViewCell.reusableCell(collectionView, indexPath: indexPath)
        cell?.delegate = self
        let objc = dataSource[indexPath.item]
        cell?.updateCellData(title: objc["title"] as! String, value: objc["value"] ?? "", indexPath.item)
        return cell ?? collectionView.dequeueReusableCell(withReuseIdentifier: STPersonalCollectionViewCell.identifier, for: indexPath)
    }
    
    // STPersonaChangeImageDelegate
    func handleChangeImageAction(indexPath: IndexPath) {
        self.showPickPictrueSheet()
    }
    
    override func handleImagePickerResult (_ image: UIImage, _ filePath: String) {
        let cell = listView.visibleCells[0] as! STPersonalCollectionViewCell
        cell.iconBtn.setImage(image, for: UIControl.State.normal)
        requestApi.updateAvatar(image) {
            (isSuccess, response, error)  in
            if(isSuccess) {
                let responseData = response as! Dictionary<String, Any>
                let imgUrl = responseData["imgUrl"] as! String
                self.dataSource[0]["value"] = imgUrl
                NotificationCenter.default.post(name: NSNotification.Name("ChangeTouxiangNotificationName"), object: nil, userInfo: ["filePath": imgUrl])
            }
        }
    }
    
    func requestUserInfo() {
        requestApi.getUserInfo() {
            (isSuccess, response, error)  in
            if(isSuccess) {
                let responseData = response as! Dictionary<String, Any>
                let data = responseData["data"] as! Dictionary<String, Any>
                self.dataSource = [[ "title": "更换头像", "value": data["avatar"] ], [ "title": "姓名", "value": data["name"] ], [ "title": "手机号", "value": data["driverTel"] ] , ["title": "居住地", "value": data["address"] ]  ]
                self.listView.reloadData()
            }
        }
    }
    
    // 懒加载
    lazy var listView: UICollectionView = {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        let collectView: UICollectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = UIColor.white
        collectView.layer.cornerRadius = 8
        return collectView
    }()
    
    lazy var loginOutBtn: UIButton = {
        let btn = UIButton.init(type: .custom)
        btn.setTitle("退出登录", for: .normal)
        btn.backgroundColor = UIColor.init(hexString: "#FF3030", alpha: 1)
        btn.layer.cornerRadius = 18
        btn.setTitleColor(UIColor.white, for: UIControl.State.normal)
        return btn
    }()
}
